package controller;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import beans.HistoryTask;
import beans.RunningTask;
import dao.HistoryTaskDao;
import engine.BIEngine0_1.TaskThread;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * Servlet implementation class GetTaskState
 */
public class GetNewestState extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GetNewestState() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String taskHash = request.getParameter("taskHash");
		List<Object> taskHashes = new HistoryTaskDao().getSubTaskHashByBatchTaskHash(taskHash).getDatas();
		JSONArray resultArray = new JSONArray();
		if(taskHashes.size()<1){
			response.getWriter().write("error");
		}else{
			for(Object one:taskHashes){
				TaskThread task = RunningTask.TASKMAP.getTask((String) one);
				JSONObject oneresult = new JSONObject();
				if (task == null) {
					oneresult.put("taskHash",one);
					oneresult.put("state","finished");
				} else {
					String ss = task.getNewestState();
					if (ss == null) {
						oneresult.put("taskHash",one);
						oneresult.put("state","finished");
					} else {
						oneresult.put("taskHash",one);
						oneresult.put("state",ss);
					}
				}
				resultArray.add(oneresult);
			}
			response.getWriter().write(resultArray.toString());
		}
	}

}
